package com.into.common.csv;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.csvreader.CsvReader;

public class CSVUtil {

	/**
	 * Reads a one column csv file
	 * 
	 * @param idsFile
	 * @return
	 * @throws ParseException
	 * @throws IOException
	 */
	public static List<String> readIds(File idsFile) throws IOException {
		if (!idsFile.canRead()) {
			throw new IllegalStateException(idsFile + " can't be read.");
		}

		FileReader fileReader = null;

		try {
			fileReader = new FileReader(idsFile);
			CsvReader reader = new CsvReader(fileReader, '\t');
			List<String> toReturn = new ArrayList<String>();

			while (reader.readRecord()) {
				toReturn.add(reader.get(0));
			}
			return toReturn;
		} finally {
			if (fileReader != null)
				fileReader.close();
		}

	}

	/**
	 * reads a two columns csv (with 0 as a key column and 1 as value)
	 * 
	 * @param fileName
	 * @return
	 * @throws FileNotFoundException
	 * @throws IOException
	 * @see #readMap(String, int, int)
	 */
	public static Map<String, String> readMap(String fileName)
			throws FileNotFoundException, IOException {
		return readMap(fileName, 0, 1);
	}

	/**
	 * reads a two columns csv
	 * 
	 * @param fileName
	 * @param keyCol
	 *          key column index
	 * @param valueCol
	 *          value column index
	 * @return
	 * @throws FileNotFoundException
	 * @throws IOException
	 */
	public static Map<String, String> readMap(String fileName, int keyCol,
			int valueCol) throws FileNotFoundException, IOException {
		FileReader fileReader = null;
		try {
			fileReader = new FileReader(fileName);
			// CSVReader reader = new CSVReader(fileReader, ';', '#');
			CsvReader reader = new CsvReader(fileReader, '\t');
			Map<String, String> toReturn = new HashMap<String, String>();
			while (reader.readRecord()) {
				// List<String> line = reader.readLine();
				// toReturn.put(line.get(0), line.get(1));
				toReturn.put(reader.get(keyCol), reader.get(valueCol));
			}
			return toReturn;
		} finally {
			if (fileReader != null)
				fileReader.close();
		}
	}

}
